package com.easydl.project.service;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import com.easydl.project.amqp.model.EasydlDiscernMessageVO;
import com.easydl.project.amqp.service.EasydlAmqpService;
import com.easydl.project.kafka.service.EasydlKafkaService;
import com.easydl.project.model.EasyPictureDiscernVO;
import com.easydl.project.model.EasydlDiscernResultVO;
import com.easydl.project.utils.EasydlHttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 先去缓存拿 
 * 
 * 		缓存没拿到 ,新请求
 * 		缓存拿到
 * 			过期，从新请求，返回
 * 			没过期，返回 
 * @author fxb208
 */
@Service
public class EasydlService {
	
	Logger logger=LoggerFactory.getLogger(this.getClass());
	
	@Value("${easydl.url}")
	private String url;
	
	@Value("${easydl.accessToken.url}")
	private String accessTokenUrl;
	
	@Value("${easydl.threshold}")
	private String threshold;
	
//	@Autowired
//	private EasyTokenService easyTokenService;
	
	@Autowired
	private EasyLockTokenService easyTokenService;
	
	@Qualifier(value="easyRestTemplate")
	@Autowired
	private RestTemplate easyRestTemplate;
	
	@Autowired
	private EasydlHttpUtil easydlHttpUtil;
	
	@Autowired
	private EasydlAmqpService easydlAmqpService;
	
	@Autowired
	private EasydlKafkaService easydlKafkaService;
	
	public String maskss(byte[] arrByte) throws Exception {
		// 请求url
		Base64 base64 = new Base64();
		byte[] b = base64.encode(arrByte);
		String image = new String(b);
		Map<String, Object> map = new HashMap<>();
		map.put("image", image);
		map.put("threshold", Double.valueOf(threshold));
		ObjectMapper objectMapper=new ObjectMapper();
		String param=objectMapper.writeValueAsString(map);
		// 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
		String accessToken = "24.443c56f672488fa8d0abdb500ab8db6f.2592000.1585221184.282335-18577273";
		String result = easydlHttpUtil.post(this.url, accessToken, "application/json", param);
		System.out.println(result);
		return result;
		
	}	
	
	public List<EasyPictureDiscernVO> maskRecognition(byte[] arrByte) throws Exception {
//		try {
//			Double.valueOf("东方不败");
//		} catch (Exception e) {
//			logger.error(e.getMessage(),e);
//			return new ArrayList<>();
//		}
		// 请求url
		Base64 base64 = new Base64();
		byte[] b = base64.encode(arrByte);
		String base64Image = new String(b);
		List<EasyPictureDiscernVO> lstPictureDiscern=getPictureDiscern(base64Image);
		return lstPictureDiscern;	
	}	
	
	private List<EasyPictureDiscernVO> getPictureDiscern(String base64Image) throws JsonProcessingException{
		String accessToken =easyTokenService.getToken().getAccess_token(); 
//		HttpHeaders headers = new HttpHeaders();
//		//  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
//		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//		//  封装参数，千万不要替换为Map与HashMap，否则参数无法传递
//		MultiValueMap<String, Object> params= new LinkedMultiValueMap<String, Object>();
//		//  也支持中文
//		params.add("image", image);
//		params.add("threshold", threshold);
//		HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(params, headers);
//		//  执行HTTP请求
//		EasydlDiscernResultVO easydlDiscernResultVO=easyRestTemplate.postForObject(this.url+"?access_token=" + accessToken, requestEntity, EasydlDiscernResultVO.class);
//		if("110".equals(easydlDiscernResultVO.getError_code())) {
//			accessToken=easyTokenService.reflashToken().getAccess_token();
//			easydlDiscernResultVO=easyRestTemplate.postForObject(this.url+"?access_token=" + accessToken, requestEntity, EasydlDiscernResultVO.class);
//		}
//		logger.info(easydlDiscernResultVO.toString());
		Map<String, Object> map = new HashMap<>();
		map.put("image", base64Image);
		logger.info("threshold:"+Double.valueOf(threshold));
		map.put("threshold", Double.valueOf(threshold));
		ObjectMapper objectMapper=new ObjectMapper();
		String param=objectMapper.writeValueAsString(map);
		EasydlDiscernResultVO easydlDiscernResultVO=easyRestTemplate.postForObject(this.url+"?access_token=" + accessToken, param, EasydlDiscernResultVO.class);
		
		//结果集发送给消息中间件
		EasydlDiscernMessageVO easydlDiscernMessageVO=new EasydlDiscernMessageVO();
		easydlDiscernMessageVO.setBase64Image(base64Image);
		easydlDiscernMessageVO.setError_code(easydlDiscernResultVO.getError_code());
		easydlDiscernMessageVO.setError_msg(easydlDiscernResultVO.getError_msg());
		easydlDiscernMessageVO.setLog_id(easydlDiscernResultVO.getLog_id());
		easydlDiscernMessageVO.setResults(easydlDiscernResultVO.getResults());
		//发送给rabbitmq
		//easydlAmqpService.sendEasydlDiscernMessage(easydlDiscernMessageVO);
		//发送给kafka
		//easydlKafkaService.sendEasydlDiscernMessage(easydlDiscernMessageVO);
		
		List<EasyPictureDiscernVO> result=new ArrayList<EasyPictureDiscernVO>();
		if(StringUtils.isEmpty(easydlDiscernResultVO.getError_code())) {
			List<EasyPictureDiscernVO> lstEasyPictureDiscernVO=easydlDiscernResultVO.getResults();
			
			System.out.println(objectMapper.writeValueAsString(lstEasyPictureDiscernVO));
			
			for(int i=0;i<lstEasyPictureDiscernVO.size();i++) {
				EasyPictureDiscernVO easyPictureDiscernVO=lstEasyPictureDiscernVO.get(i);
				logger.info(easyPictureDiscernVO.toString());
				if("unmask".equals(easyPictureDiscernVO.getName()) && easyPictureDiscernVO.getScore().doubleValue()>0.8) {
					result.add(easyPictureDiscernVO);
				}
			}
		}else {
			logger.info("请求报错Error_code:"+easydlDiscernResultVO.getError_code());
			logger.info("请求报错Error_msg:"+easydlDiscernResultVO.getError_msg());
		}
		return result;
	}
}
